/**
 * Importação das bibliotecas necessárias para a implementação da classe.
 */
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.logging.Logger;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 17/05/2011, 14:24:47
 */


/**
 * 
 * Universidade de Brasília - Gama
 * Sistema de Análise de Investimentos de Bolsa de Valores - Projeto de Técnicas de Programação
 * @author Filipe Barbosa de Almeida - 09/0006097
 * @author Gabriela Matias Navarro - 09/0006526
 * @author Renato Guibson Girardi - 09/0013204
 */
public class Login extends JFrame{
     /**
     * Criando o Objeto log para geração de logs.
     */
    private static Logger log = Logger.getLogger(Login.class.getName());
    /**
     * Declarando atributos
     */
    private static ResourceBundle myResources;
    private static String LinguaAtual = "Português";

       Locale ptr = new Locale("pt","BR");
  /** Creates new form Login */
    public Login(String lingua) {
        
        
        LinguaAtual = lingua;
        if (lingua.equals("Português")) {
           myResources =  ResourceBundle.getBundle("Message",ptr);
        }
        else {
           myResources =  ResourceBundle.getBundle("Message_en_US",Locale.ENGLISH);
        }
        initComponents();
        
       log.info("Idioma Escolhido");
       log.info("Login Iniciado");
    }
    /**
     * Construtor
     */
    public Login() {
        this("Português");
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setBackground(new java.awt.Color(200, 200, 200));
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(400, 150));
        setName("login"); // NOI18N
        setResizable(false);

        jButton1.setText(myResources.getString("login.enter"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButton1KeyPressed(evt);
            }
        });

        jButton2.setText(myResources.getString("login.subscribe"));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.setText("");
        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTextField1MousePressed(evt);
            }
        });
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jLabel1.setText(myResources.getString("login.user"));
        jLabel1.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                jLabel1AncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel2.setText(myResources.getString("login.password"));

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SAIBV.jpg"))); // NOI18N

        jLabel16.setText(myResources.getString("message.SAIBV"));
        jLabel16.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(22, 22, 22)
                                .addComponent(jButton1)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jPasswordField1)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel16)))
                .addContainerGap(72, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName("frame2");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    //botao para ENTRAR
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jTextField1ActionPerformed
//Botão para cadastrar
    private void jLabel1AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jLabel1AncestorAdded
        // TODO add your handling code here:
    }//GEN-LAST:event_jLabel1AncestorAdded

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        
        try{
            
            /**
             * Método que faz o login (através do mouse)
             * consulta no banco de dados a existência do usuario.
             */
            Transacao.abrir();
            System.out.println("transação");
            Transacao.consultar("SELECT * FROM usuario WHERE login = '"+jTextField1.getText()+"' AND senha = '"+jPasswordField1.getText()+"'");
            String resultado = "";
            log.info("Consulta do Usuário no banco de dados realizado"); 
            //Mensagem que aparece caso o Usuario nao seja cadastrado
            if(!Transacao.getRs().next()){
                JOptionPane.showMessageDialog( null, myResources.getString("mensagem.login") );
                
                log.info("Usuário não encontrado no banco de dados");
                log.info("Login não realizado");
                
            }else {
                
                /**
                 * Método que abre a janela Principal caso o login seja realizado com sucesso
                 */
                JOptionPane.showMessageDialog( null, myResources.getString("mensagem.boas.vindas")+ " " + Transacao.getRs().getString( "nome" ) );
                Principal principal = new Principal(LinguaAtual,jTextField1.getText());
                principal.show();
                principal.setLocationRelativeTo(null);
                 dispose();
                
                log.info("Usuário encontrado no banco de dados");
                log.info("Login finalizado");
           /** do{
                resultado += "nome: " + Transacao.getRs().getString("nome");
                resultado += "\nusuario: " + Transacao.getRs().getString("login");
                resultado += "\nsenha: " + Transacao.getRs().getString("senha");
                resultado +="\nsexo: "+ Transacao.getRs().getString("sexo");
                resultado += "\n.........";
            }while( Transacao.getRs().next() );
            */
            
        }
            
            System.out.println( resultado );
        }catch( Exception e ){
            System.out.println( e.getMessage() );
        }
        
        
}//GEN-LAST:event_jButton1ActionPerformed

    /**
     * Método que abre a janela cadastrar.
     * @param evt 
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        log.info("Solicitação de Cadastro realizada"); 
        // TODO add your handling code here:
        Cadastro cadastro = new Cadastro(LinguaAtual);
        cadastro.show();
        cadastro.setLocationRelativeTo(null);
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1MousePressed

    private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1KeyPressed
        // TODO add your handling code here:
                try{
           
              /**
             * Método que faz o login (através do teclado)
             * consulta no banco de dados a existência do usuario.
             */
            Transacao.abrir();
            System.out.println("transação");
            Transacao.consultar("SELECT * FROM usuario WHERE login = '"+jTextField1.getText()+"' AND senha = '"+jPasswordField1.getText()+"'");
            String resultado = "";
            
            log.info("Consulta do Usuário no Banco de Dados realizada");
            //Mensagem que aparece caso o Usuario nao seja cadastrado
            if(!Transacao.getRs().next()){
                JOptionPane.showMessageDialog( null, myResources.getString("mensagem.login") );
                
                
                log.info("Usuário não encontrado no banco de dados");
                log.info("Login não realizado");
            
            }else {
                
                /**
                 * Método que abre a janela Principal caso o Login seja realizado com sucesso
                 */
                JOptionPane.showMessageDialog( null, myResources.getString("mensagem.boas.vindas") + Transacao.getRs().getString( "nome" ) );
                Principal principal = new Principal(LinguaAtual,jTextField1.getText());
                 principal.show();
                 dispose();
                 
                log.info("Usuário encontrado no banco de dados");
                log.info("Login finalizado");
                log.info ("Programa Iniciado");
                        
            do{
                resultado += "nome: " + Transacao.getRs().getString("nome");
                resultado += "\nusuario: " + Transacao.getRs().getString("login");
                resultado += "\nsenha: " + Transacao.getRs().getString("senha");
                resultado +="\nsexo: "+ Transacao.getRs().getString("sexo");
                resultado += "\n.........";
            }while( Transacao.getRs().next() );
            
            
        }
            
            System.out.println( resultado );
        }catch( Exception e ){
            System.out.println( e.getMessage() );
        }
        
        
    }//GEN-LAST:event_jButton1KeyPressed

    
    //Lista para as linguagens 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) { //  throws SQLException {
        
     
       
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Login login = new Login();
                login.setVisible(true);
                
                }
        });
    }
   
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables


}
